"""
To get the pictures of National Geographics
"""

import threading
import ctypes
import Image
import calendar
import urllib
import socket
import os

class MonthPicture(threading.Thread):
    STOREDIR = 'C:/lg_wallpaper/pod/'
    def __init__(self,year,month):
        threading.Thread.__init__(self)
        self.year = year
        self.month = month
        
    def run(self):
        for d in range(1,32):
            print self.year,self.month,d 
            self.getPictureByDate(self.year, self.month, d)

    def getPictureByDate(self,yy,mm,dd):
        print 'getting the picture of ',yy,mm,dd
        try:
            pageurl = 'http://lava.nationalgeographic.com/cgi-bin/pod/wallpaper.cgi?day='+str(dd)+'&month='+str(mm)+'&year='+str(yy)
            sock = urllib.urlopen(pageurl)
            htmlSource = sock.read()
            sock.close()    
            pos1 = htmlSource.find('lg_wallpaper')
            pos2 = htmlSource.find('pod_1024x768_icon')
            filename = htmlSource[pos1+13:pos2-24]
            fileurl = 'http://lava.nationalgeographic.com/pod/pictures/lg_wallpaper/'+filename
            fname = self.STOREDIR + filename
            urllib.urlretrieve(fileurl, fname)
            print 'got the picture from ' + fileurl
            return fname
        except Exception, e:
            print e
            print "fail to getting picture of ",yy,mm,dd
            pass            

mp = range(1,13)
print mp
for i in range(1,13):
    print '===========',i
    mp[i-1]=MonthPicture(1,i)
    mp[i-1].start()


